/**
 * Created with JetBrains WebStorm.
 * User: MTROL
 * Date: 11/15/13
 * Time: 2:41 PM
 * To change this template use File | Settings | File Templates.
 */

var sfs = null;
var currentPrivateChat;
var privateChats;
var inGame = false;
var myInfo;

function init() {
    trace("Application started");

    // Create configuration object
    var config = {};
    config.host = "geometrychess.com";
//    config.host = "127.0.0.1";
    config.port = 8888;
    config.zone = "BasicExamples";
    config.debug = false;

    // Create SmartFox client instance
    sfs = new SmartFox(config);

    // Add event listeners
    sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this);
    sfs.addEventListener(SFS2X.SFSEvent.CONNECTION_LOST, onConnectionLost, this);
    sfs.addEventListener(SFS2X.SFSEvent.LOGIN_ERROR, onLoginError, this);
    sfs.addEventListener(SFS2X.SFSEvent.LOGIN, onLogin, this);
    sfs.addEventListener(SFS2X.SFSEvent.LOGOUT, onLogout, this);
    sfs.addEventListener(SFS2X.SFSEvent.ROOM_JOIN_ERROR, onRoomJoinError, this);
    sfs.addEventListener(SFS2X.SFSEvent.ROOM_JOIN, onRoomJoin, this);
    sfs.addEventListener(SFS2X.SFSEvent.PUBLIC_MESSAGE, onPublicMessage, this);
    sfs.addEventListener(SFS2X.SFSEvent.PRIVATE_MESSAGE, onPrivateMessage, this);
    sfs.addEventListener(SFS2X.SFSEvent.USER_ENTER_ROOM, onUserEnterRoom, this);
    sfs.addEventListener(SFS2X.SFSEvent.USER_EXIT_ROOM, onUserExitRoom, this);
    sfs.addEventListener(SFS2X.SFSEvent.ROOM_VARIABLES_UPDATE, onRoomVariableUpdate, this);
//    sfs.addEventListener(SFS2X.SFSEvent.USER_COUNT_CHANGE, onUserCountChange, this);

    sfs.addEventListener(SFS2X.SFSEvent.EXTENSION_RESPONSE, onExtensionRs, this);

    trace("SmartFox API version: " + sfs.version);

    // Show LOGIN view
    setView("loginparent", true);
    sfs.connect();
}

function onExtensionRs(event) {
    LOG("extension response: " + event.cmd);
    if (event.cmd == command.start) {
        startGameListener(event);
    } else if (event.cmd == command.move) {
        onMovePieceListener(event);
    } else if (event.cmd == command.error) {
        onErrorListener(event);
    } else if (event.cmd == command.setting) {
        onSettingListener(event);
    } else if (event.cmd == command.finish) {
//        setTimeout(onEndGameListener(event), 5000);
        onEndGameListener(event);
    } else if (event.cmd == command.lobbyUserChange) {
        updateRoomList(event);
    } else if (event.cmd == command.userInGroup) {
        populateRoomsList(event);
    } else if (event.cmd == command.ready){
        onReadyListener();
    }
}

function onReadyListener(){
    LOG("on ready listener");
    com.isReady = true;
    if(com.myColor==Red){
        var pos = getPosOfCell(3, 4);
        com.context.clearRect(pos.x, pos.y, 180, 60);
    }

    for (var i = 0; i < com.listUser.length; i++) {
        if (com.listUser[i].name == com.myProfile.name) {
            drawAvatarReady(com.myColor==Blue, com.listUser[i]);
            break;
        }
    }
}

function onEndGameListener(event) {
    var response = event.params;
    LOG("end game listener. WinnerId: " + response.winner);
    writeToGameChatArea("<strong>Kết thúc ván cờ. Bạn " + (com.myProfile.id == response.winner ? "thắng" : "thua") + "</trong>");
    clearInterval(timer.countDown);
    drawFinishGame(com.myProfile.id == response.winner);
    setTimeout(restartGame, 5000);

    for (var i = 0; i < com.listUser.length; i++) {
        if (com.listUser[i].name != com.myProfile.name) {
            drawAvatar(true, com.listUser[i]);
            break;
        }
    }
}

function onSettingListener(event) {
    var response = event.params;
    com.setting.totalTime = response.total;
    com.setting.turnTime = response.turn;
    com.setting.point = response.point;

    updateSetting();
//    newGame();
}

//handle error from server
function onErrorListener(event) {
    LOG("on error listener response");
    var response = event.params;
    LOG();
    alert(response.message);
}

//handle move piece
function onMovePieceListener(event) {
    var response = event.params;
    LOG("src location before change: " + response.posX + ", " + response.posY);
    var pSrc = changePosServerToClient(new Location(response.posX, response.posY), com.myColor);
    var pDes = changePosServerToClient(new Location(response.desX, response.desY), com.myColor);
    LOG("src location: " + pSrc.x + ", " + pSrc.y);
    com.piece = getPieceAtLocation(pSrc);
    LOG("piece has detected: " + com.piece);
    var point = response.pointAtMove;
    var geoNumber = response.geoNumber;
    LOG("number geo: " + geoNumber + ", point at move: " + point);
    if (com.piece != null) {
        if (com.geos != null) {
            for (var i = 0; i < com.geos.length; i++) {
                var lisPieceHit = com.geos[i];
                for (var j = 0; j < lisPieceHit.length; j++) {
                    LOG("piece hit Id: " + lisPieceHit[j]);
                    var loHighLight = getLocationById(lisPieceHit[j]);
                    if (loHighLight != null) {
                        removeHighLight(loHighLight);
                    }
                }
            }
            com.geos = null;
        }
        com.piece.movePiece(pDes);
        //neu canMove thi day la luot di cua minh.
        if (point > 0) {
            if (com.canMove) {
                if (com.myColor == Blue) {
                    com.score.blue += point;
                    if (com.winRound1 == null && com.score.blue >= 5) {
                        com.winRound1 = Blue;
                    } else if (com.winRound2 == null && com.score.blue >= 10) {
                        com.winRound2 = Blue;
                    }
                    drawGButton(Blue, com.score.blue, point);
                } else {
                    com.score.red += point;
                    if (com.winRound1 == null && com.score.red >= 5) {
                        com.winRound1 = Red;
                    } else if (com.winRound2 == null && com.score.red >= 10) {
                        com.winRound2 = Red;
                    }
                    drawGButton(Red, com.score.red, point);
                }
            } else {
                if (com.myColor != Blue) {
                    com.score.blue += point;
                    if (com.winRound1 == null && com.score.blue >= 5) {
                        com.winRound1 = Blue;
                    } else if (com.winRound2 == null && com.score.blue >= 10) {
                        com.winRound2 = Blue;
                    }
                    drawGButton(Blue, com.score.blue, point);
                } else {
                    com.score.red += point;
                    if (com.winRound1 == null && com.score.red >= 5) {
                        com.winRound1 = Red;
                    } else if (com.winRound2 == null && com.score.red >= 10) {
                        com.winRound2 = Red;
                    }
                    drawGButton(Red, com.score.red, point);
                }
            }

            //draw highlight when hit geo
            com.geos = response.geos;
            for (var i = 0; i < com.geos.length; i++) {
                var lisPieceHit = com.geos[i];
                for (var j = 0; j < lisPieceHit.length; j++) {
                    LOG("piece hit Id: " + lisPieceHit[j]);
                    var loHighLight = getLocationById(lisPieceHit[j]);
                    if (loHighLight != null) {
                        drawHighLight(loHighLight);
                    }
                }
            }
        }
        com.piece = null;
        com.canMove = !com.canMove;
        com.setting.times[2] = com.setting.turnTime;
    } else {
        LOG("piece response null");
    }
}

//handle start game response from server
function startGameListener(event) {
    LOG("start game command");
    var response = event.params;
    com.startId = response.startId;
    if (com.myProfile.id == com.startId) {
        com.canMove = true;
    } else {
        com.canMove = false;
    }

    com.isPlay = true;
    var pos = getPosOfCell(3, 4);
    com.context.clearRect(pos.x, pos.y, 180, 60);
    timer.countDown = setInterval(countDownTime, 1000);

    for (var i = 0; i < com.listUser.length; i++) {
        //if (com.listUser[i].name != com.myProfile.name) {
            drawAvatar(true, com.listUser[i]);
            break;
        //}
    }
//    com.context.fillRect(pos.x, pos.y, 60, 60);
//    com.context.fillRect(pos.x+120, pos.y, 60, 60);
}


/**
 * Connect button click handler.
 * Connects to a SFS2X instance.
 */
function onConnectBtClick() {
    // Connect to SFS
    // As no parameters are passed, the config object is used
    sfs.connect();

    // Hide any previous error
    $("#errorLb").hide();

    // Disable button
    enableButton("#connectBt", false);
}

/**
 * Login button click handler.
 * Performs the login, which in turn (see onLogin event) makes the view switch to the lobby.
 */
function onLoginBtClick() {
    // Hide any previous error
    $("#errorLb").hide();

    // Perform login
    var uName = $("#usernameIn").val();
    var pWord = $("#passwordIn").val();
    var isSent = sfs.send(new SFS2X.Requests.System.LoginRequest(uName, pWord, null, 'BasicExamples'));

    if (isSent) {
        // Disable interface
        enableTextField("#usernameIn", false);
        enableTextField("#passwordIn", false);
        enableButton("#loginBt", false);
    }
}

/**
 * Disconnect button click handler.
 * Disconnects the client from the SFS2X instance.
 */
function onRegisterBtClick() {
    window.open("register.php");
}
function onDisconnectBtClick() {
    // Disconnect from SFS
    sfs.disconnect();

    // Hide any previous error
    $("#errorLb").hide();

    // Disable button
    enableButton("#disconnectBt", false);
}

/**
 * Logout button click handler.
 * Performs the logout, which in turn (see onLogout event) makes the view switch to the login box.
 */
function onLogoutBtClick() {
    var isSent = sfs.send(new SFS2X.Requests.System.LogoutRequest());

    if (isSent)
        enableButton("#logoutBt", false);
}

/**
 * Public message send button click handler.
 * Send a public message, which will be displayed in the chat area (see onPublicMessage event).
 */
function onSendPublicMessageBtClick(event) {
    if (inGame == false && $("#publicMsgIn").val() != "") {
        var isSent = sfs.send(new SFS2X.Requests.System.PublicMessageRequest($("#publicMsgIn").val()));

        if (isSent)
            $("#publicMsgIn").val("");
    }
    else if (inGame == true && $("#gameMsgIn").val() != "") {
        var isSent = sfs.send(new SFS2X.Requests.System.PublicMessageRequest($("#gameMsgIn").val()));

        if (isSent)
            $("#gameMsgIn").val("");
    }
}

/**
 * When a user is selected in the user list, enable the button to challenge him in a new game.
 * In the game creation window the game is automatically set to private and the user is selected in the invitees list.
 */
function onUserSelected(event) {
    var args = event.args;
    var selectionType = args.type;
    var selectedindex = $("#userList").jqxListBox("getSelectedIndex");
    // Only consider user selection made using mouse or keyboard (API call is excluded)
    if (selectionType != "none") {
        var item = $("#userList").jqxListBox("getItem", args.index);
        var user = item.originalItem.userObj;

        // Enable private chat
        if (currentPrivateChat != user.id)
            enablePrivateChat(user.id);

        // For example code simplicity we rebuild the full userlist instead of just editing the specific item
        // This causes # of PM to read being updated
        populateUsersList();
    }
    $("#userList").jqxListBox("unselectIndex",selectedindex);
}

function onSendPrivateMessageBtClick(event) {
    var isSent = sfs.send(new SFS2X.Requests.System.PrivateMessageRequest($("#privateMsgIn").val(), currentPrivateChat, {recipient: currentPrivateChat}));

    if (isSent)
        $("#privateMsgIn").val("");
}

function onDeselectUserBtClick(event) {
    enablePrivateChat(-1);
}

/**
 * When a room is selected in the room list, the "Play" and "Watch" buttons are enabled
 */
function onBigRoomSelected(event) {
    var doEnable = event != undefined;

    if (!doEnable) {
        selectedRoom = null;
//        $("#bigroomList").jqxListBox("clearSelection");
    }

    joinbigroom();
}
function onRoomSelected(event) {
    var doEnable = event != undefined;
    if (!doEnable) {
        selectedRoom = null;
        $("#roomList").jqxListBox("clearSelection");
    }

    ondoubleclick();
}
function ondoubleclick() {
    if ($("#roomList").jqxListBox("selectedIndex") > -1) {
        // Join selected room
        var room = $("#roomList").jqxListBox("getSelectedItem").originalItem.roomObj;
        sfs.send(new SFS2X.Requests.System.JoinRoomRequest(room));
        sfs.lastJoinedRoom = room.name;
        populateUsersList();
    }
}
function onPlayGameBtClick(event) {
    if ($("#roomList").jqxListBox("selectedIndex") > -1) {
        // Join selected room
        var room = $("#roomList").jqxListBox("getSelectedItem").originalItem.roomObj;
        sfs.send(new SFS2X.Requests.System.JoinRoomRequest(room));
    }
}

function onWatchGameBtClick(event) {
    if ($("#roomList").jqxListBox("selectedIndex") > -1) {
        // Join selected room
        var room = $("#roomList").jqxListBox("getSelectedItem").originalItem.roomObj;
        sfs.send(new SFS2X.Requests.System.JoinRoomRequest(room, "", sfs.lastJoinedRoom.id, true));
    }
}

//function onDeselectGameBtClick(event) {
//    onRoomSelected(null);
//}

/**
 * Enter a random game among those available.
 */
function onQuickJoinBtClick(event) {
    sfs.send(new SFS2X.Requests.Game.QuickJoinGameRequest(null, [GAME_ROOMS_GROUP_NAME], sfs.lastJoinedRoom));
}

/**
 * Leave game button click handler.
 * In order to leave the current game room, the lobby room is joined.
 */
function joinbigroom() {
    if ($("#bigroomList").jqxListBox("selectedIndex") > -1) {        // Join selected room
        var room = $("#bigroomList").jqxListBox('getSelectedIndex');
        if (room == 0) {
            LOBBY_ROOM = CHO_1;
            sfs.send(new SFS2X.Requests.System.JoinRoomRequest(CHO_1));
        }
        if (room == 1) {
            LOBBY_ROOM = CHO_2;
            sfs.send(new SFS2X.Requests.System.JoinRoomRequest(CHO_2));
        }
        if (room == 2) {
            LOBBY_ROOM = CHO_3;
            sfs.send(new SFS2X.Requests.System.JoinRoomRequest(CHO_3));
        }
        if (room == 3) {
            LOBBY_ROOM = CHO_4;
            sfs.send(new SFS2X.Requests.System.JoinRoomRequest(CHO_4));
        }
        if (room == 4) {
            LOBBY_ROOM = CHO_5;
            sfs.send(new SFS2X.Requests.System.JoinRoomRequest(CHO_5));
        }
        if (room == 5) {
            LOBBY_ROOM = CHO_6;
            sfs.send(new SFS2X.Requests.System.JoinRoomRequest(CHO_6));
        }

    }

}
function onLeaveGameBtClick(event) {
    // Join the lobby
    joinLobbyRoom();

    //Remove Game Popup
//    removeGamePopUp();
}

/**
 * Create game button click handler.
 * Shows the game room creation panel.
 */

/**
 * When the game creation panel is closed, all the form items it contains are reset to default values.
 */
/**
 * Create game button click event listener (create game panel).
 * Create a new game using the parameters entered in the game creation popup window.
 */
//function onDoCreateGameBtClick(event) {
//    if ($("#gameNameIn").val() != "") {
//        // Basic game settings
//        var settings = new SFS2X.Requests.Game.SFSGameSettings($("#gameNameIn").val());
//        settings.groupId = GAME_ROOMS_GROUP_NAME;
//        settings.isGame = true;
//        settings.maxUsers = 2;
//        settings.maxSpectators = Number($("#spectatorsIn").jqxNumberInput("val"));
//
//        //Extension
//        settings.extension = new SFS2X.Requests.RoomExtension(EXTENSION_ID, EXTENSIONS_CLASS);
//
//        // Send CreateSFSGame request
//        var isSent = sfs.send(new SFS2X.Requests.Game.CreateSFSGameRequest(settings));
//
//        // Close panel
//        if (isSent)
//            $("#createGameWin").jqxWindow("closeWindow");
//    }
//}

//------------------------------------
// SFS EVENT HANDLERS
//------------------------------------

function onConnection(event) {
    // Reset view
    setView("loginparent", false);

    if (event.success) {
        trace("Connected to SmartFoxServer 2X!");
    }
    else {
        var error = "Connection failed: " + (event.errorMessage ? event.errorMessage + " (code " + event.errorCode + ")" : "Is the server running at all?");
        showError(error);
    }
}

function onConnectionLost(event) {
    // Reset view
    setView("loginparent", true);

    enablePrivateChat(-1);
    onRoomSelected(null);
    // Show disconnection reason
    if (event.reason != SFS2X.Utils.ClientDisconnectionReason.MANUAL && event.reason != SFS2X.Utils.ClientDisconnectionReason.UNKNOWN) {
        var error = "You have been disconnected; reason is: " + event.reason;
        showError(error);
    }
    else
        trace("You have been disconnected; reason is: " + event.reason);
}

function onLoginError(event) {
    // Reset view
    setView("loginparent", true);

    // Show error
    var error = "Login error: " + event.errorMessage + " (code " + event.errorCode + ")";
    showError(error);
}

function onLogin(event) {
    trace("Login successful!" +
        "\n\tZone: " + event.zone +
        "\n\tUser: " + event.user +
        "\n\tuserVariable: " + event.user);
    myInfo = event.user;
    com.myProfile = event.user;

    // Set user name
    // NOTE: this always a good practice, in case a custom login procedure on the server side modified the username
    $("#usernameIn").val(event.user.name);

    // Check if the "game" group is already subscribed;
    // if not, subscribe it
//    if (!sfs.roomManager.containsGroup(GAME_ROOMS_GROUP_NAME))
//        sfs.send(new SFS2X.Requests.System.SubscribeRoomGroupRequest(GAME_ROOMS_GROUP_NAME));

    // Join lobby room
    joinLobbyRoom();

    // Private Chat system
    currentPrivateChat = -1;
    privateChats = [];
}

function onLogout(event) {
    trace("Logout from zone " + event.zone + " performed!");

    // Switch to LOGIN view
    setView("loginparent", true);

    enablePrivateChat(-1);
    onRoomSelected(null);
}

function onRoomJoinError(event) {
    trace("Room join error: " + event.errorMessage + " (code: " + event.errorCode + ")", true);

    // Reset roomlist selection
//    onRoomSelected(null);
    leaveLobbyRoom();
    joinLobbyRoom();
}

function onRoomJoin(event) {
    trace("Room joined: " + event.room);
    trace("user variable: " + myInfo.getVariables());

    // Switch view
    if (event.room.name == CHO_1 || event.room.name == CHO_2
        || event.room.name == CHO_3 || event.room.name == CHO_4
        || event.room.name == CHO_5 || event.room.name == CHO_6) {
        inGame = false;

        $("#roomLb").html(event.room.name);
        setView("lobby", true);
        if (event.room.name == CHO_1) {
            writeToLobbyChatArea("Bạn vừa vào Giản đơn 1");
        }
        if (event.room.name == CHO_2) {
            writeToLobbyChatArea("Bạn vừa vào Giản đơn 2");
        }
        if (event.room.name == CHO_3) {
            writeToLobbyChatArea("Bạn vừa vào Giản đơn 3");
        }
        if (event.room.name == CHO_4) {
            writeToLobbyChatArea("Bạn vừa vào Chuẩn 1");
        }
        if (event.room.name == CHO_5) {
            writeToLobbyChatArea("Bạn vừa vào Chuẩn 2");
        }
        if (event.room.name == CHO_6) {
            writeToLobbyChatArea("Bạn vừa vào Chuẩn 3");
        }
        // Remove Game Popup
//        removeGamePopUp();
        var param = {};
        param.groupId = event.room.groupId;
        sfs.send(new SFS2X.Requests.System.ExtensionRequest(command.userInGroup, param));
    }
    else {
        inGame = true;
        setView("game", true);
        writeToGameChatArea("Bạn vừa vào '" + event.room.name + "'");
        // Reset roomlist selection
        onRoomSelected(null);

        //check user is player or spectator, get setting room.
        com.listUser = event.room.getUserList();
        //TODO check lai nguoi choi hoac nguoi xem bang cach khac
        if (com.listUser.length == 1) {
            com.myColor = Blue;
        } else if (com.listUser.length == 2) {
            com.myColor = Red;
        }

        com.setting = {};
        if (event.room.containsVariable(command.type)) {
            com.setting.type = event.room.getVariable(command.type).value;
        }
        if (event.room.containsVariable(command.setting)) {
            var st = event.room.getVariable(command.setting).value;
            com.setting.point = st.point;
            com.setting.totalTime = st.total;
            com.setting.turnTime = st.turn;
        }
        com.isPlay = false;
        trace("request start game");
        com.init();
    }
}

function onPublicMessage(event) {
    var sender = (event.sender.isItMe ? myInfo.name : event.sender.name);
    var sender = (event.sender.name);
    var msg = "<b>" + sender + " :</b> " + event.message;

    if (event.room.name == CHO_1 || event.room.name == CHO_2
        || event.room.name == CHO_3 || event.room.name == CHO_4
        || event.room.name == CHO_5 || event.room.name == CHO_6)
        writeToLobbyChatArea(msg);
    else
        writeToGameChatArea(msg);
}

function onPrivateMessage(event) {
    var user;

    if (event.sender.isItMe) {
        var userId = event.data.recipient;
        var user = sfs.userManager.getUserById(userId);
    }
    else
        user = event.sender;

    if (privateChats[user.id] == null)
        privateChats[user.id] = {queue: [], toRead: 0};

    var message = "<b>" + (event.sender.isItMe ? myInfo.name : event.sender.name) + " :</b> " + event.message;
    privateChats[user.id].queue.push(message);

    if (currentPrivateChat == user.id)
        writeToPrivateChatArea(message);
    else {
        privateChats[user.id].toRead += 1;

        // For example code simplicity we rebuild the full userlist instead of just editing the specific item
        // This causes # of PM to read being displayed
        populateUsersList();
    }
}

function onUserEnterRoom(event) {
    if (event.room.name == CHO_1 || event.room.name == CHO_2 || event.room.name == CHO_3
        || event.room.name == CHO_4 || event.room.name == CHO_5 || event.room.name == CHO_6) {
        writeToLobbyChatArea("<em>User " + event.user.name + " (" + event.user.id + ") vừa vào phòng</em>");

        // For example code simplicity we rebuild the full userlist instead of just adding the specific item
        populateUsersList();
    }
    else {
        writeToGameChatArea("<em>User " + event.user.name + " (" + event.user.id + ") vừa vào phòng</em>");
        //TODO draw user avatar and notify user enter room
        if (event.user.isPlayer()) {
            drawAvatar(true, event.user);
        }
    }
}

function onRoomVariableUpdate(event) {
    LOG("on room variable update");
}

function onUserExitRoom(event) {
    if (event.room.name == CHO_1 || event.room.name == CHO_2 || event.room.name == CHO_3
        || event.room.name == CHO_4 || event.room.name == CHO_5 || event.room.name == CHO_6) {
        if (!event.user.isItMe)
            writeToLobbyChatArea("<em>User " + event.user.name + " đã rời phòng</em>");

        // For example code simplicity we rebuild the full userlist instead of just removing the specific item
        populateUsersList();
    }
    else {
        if (!event.user.isItMe)
            writeToGameChatArea("<em>User " + event.user.name + " đã rời phòng</em>");

        //TODO user leave room or disconnect
        removeAvatar();
        userLeaveRoom();
    }

    // Disable private chat
    if (event.user.isItMe || event.user.id == currentPrivateChat)
        enablePrivateChat(-1);
}

//function onUserCountChange(event) {
//    // For example code simplicity we rebuild the full roomlist instead of just updating the specific item
////    populateRoomsList();
//}

//function onRoomRemove(event) {
//    trace("Room removed: " + event.room);
//
//    // For example code simplicity we rebuild the full roomlist instead of just removing the item
//    populateRoomsList();
//}
//
//function onRoomAdd(event) {
//    trace("Room added: " + event.room);
//
//    // For example code simplicity we rebuild the full roomlist instead of just adding the new item
//    populateRoomsList();
//
//    if (event.room.id == selectedRoom.id)
//        onRoomSelected(null);
//}


//------------------------------------
// OTHER METHODS
//------------------------------------

function trace(txt, showAlert) {
    console.log(txt);

    if (showAlert)
        alert(txt);
}

function showError(text) {
    trace(text);
    $("#errorLb").html("<b>ATTENTION</b><br/>" + text);
    $("#errorLb").toggle();
}

function setView(viewId, doSwitch) {
    // Check connection/login status to enable interface elements properly
    if (viewId == "loginparent") {
        // Connect and disconnect buttons
        enableButton("#connectBt", !sfs.isConnected());
        enableButton("#disconnectBt", sfs.isConnected());

        // Login textinput and button
        enableTextField("#usernameIn", (sfs.isConnected() && sfs.mySelf == null));
        enableTextField("#passwordIn", (sfs.isConnected() && sfs.mySelf == null));
        enableButton("#loginBt", (sfs.isConnected() && sfs.mySelf == null));

        // Hide create game window if open
        $("#createGameWin").jqxWindow("closeWindow");
    }
    else if (viewId == "lobby") {
        // Logout button
        enableButton("#logoutBt", (sfs.isConnected() && sfs.mySelf != null));

        // Chat area
        enableChatArea((sfs.isConnected() && sfs.lastJoinedRoom != null), doSwitch);

        if (sfs.isConnected() && sfs.mySelf != null) {
            // Populate room & user lists
//            populateRoomsList();
            populateUsersList();
            populateBigRoomList();
            onAvatar();
        }
        else {
            // Clear room & user lists
            $("#roomList").jqxListBox("clear");
            $("#userList").jqxListBox("clear");
            $("#bigroomlist").jqxListBox("clear");
        }
    }
    else if (viewId == "game") {
        // Chat area
        enableChatArea((sfs.isConnected() && sfs.lastJoinedRoom != null), doSwitch);
    }

    // Switch view
    if (doSwitch)
        switchView(viewId);
}

function switchView(viewId) {
    if ($("#" + viewId).length <= 0)
        return;

    $('.viewStack').each(function (index) {
        if ($(this).attr("id") == viewId) {
            $(this).show();
            $(this).css({opacity: 1}); // Opacity attribute is used on page load to hide the views because display:none causes issues to the NavigationBar widget
        }
        else {
            $(this).hide();
        }
    });
}

function enableButton(id, doEnable) {
    $(id).jqxButton({disabled: !doEnable});
}

function enableTextField(id, doEnable) {
    if (doEnable)
        $(id).removeAttr("disabled");
    else
        $(id).attr("disabled", true);
}

function enableChatArea(doEnable, clear) {
    if (inGame == false) {
        if (clear) {
            $("#publicChatAreaPn").jqxPanel("clearcontent");
            $("#publicMsgIn").val("");
        }

        $("#publicChatAreaPn").jqxPanel({disabled: !doEnable});

        enableTextField("#publicMsgIn", doEnable);
        enableButton("#sendPublicMsgBt", doEnable);
    }
    else {
        if (clear) {
            $("#gameChatAreaPn").jqxPanel("clearcontent");
            $("#gameMsgIn").val("");
        }

        $("#gameChatAreaPn").jqxPanel({disabled: !doEnable});

        enableTextField("#gameMsgIn", doEnable);
        enableButton("#sendGameMsgBt", doEnable);
    }
}

function enablePrivateChat(userId) {
    currentPrivateChat = userId;

    doEnable = (userId > -1);

    // Clear current chat
    $("#privChatAreaPn").jqxPanel("clearcontent");

    if (!doEnable) {
        $("#privateMsgIn").val("");
        $("#userList").jqxListBox("clearSelection");
        $("#privChatUserLb").html("");
    }
    else {
        $("#privChatUserLb").html("with <b>" + sfs.userManager.getUserById(userId).name + "</b>");

        // Fill chat with history
        if (privateChats[userId] != null) {
            privateChats[userId].toRead = 0;

            for (var i = 0; i < privateChats[userId].queue.length; i++)
                writeToPrivateChatArea(privateChats[userId].queue[i]);
        }
    }

    $("#privChatAreaPn").jqxPanel({disabled: !doEnable});

    enableTextField("#privateMsgIn", doEnable);
    enableButton("#sendPrivMsgBt", doEnable);
    enableButton("#deselectUserBt", doEnable);
}

//function joinroombyname(event) {
//    if (sfs.lastJoinedRoom == null || sfs.lastJoinedRoom.name != event)
//        sfs.send(new SFS2X.Requests.System.JoinRoomRequest(event));
//}

function joinLobbyRoom() {
    if (LOBBY_ROOM == null) {
        LOG("lobby room null");
        LOBBY_ROOM = CHO_1;
    }
    if (sfs.lastJoinedRoom == null || sfs.lastJoinedRoom.name != LOBBY_ROOM) {
        sfs.send(new SFS2X.Requests.System.JoinRoomRequest(LOBBY_ROOM));
    }
}

function leaveLobbyRoom() {
    if (LOBBY_ROOM == null) {
        LOG("lobby room null");
        LOBBY_ROOM = CHO_1;
    }
    if (sfs.lastJoinedRoom == null || sfs.lastJoinedRoom.name != LOBBY_ROOM) {
        sfs.send(new SFS2X.Requests.System.LeaveRoomRequest(LOBBY_ROOM));
    }
}

function writeToLobbyChatArea(text) {
    $("#publicChatAreaPn").jqxPanel("append", "<p class='chatAreaElement'>" + text + "</p>");

    // Set chat area scroll position
    $("#publicChatAreaPn").jqxPanel("scrollTo", 0, $("#publicChatAreaPn").jqxPanel("getScrollHeight"));
}

function writeToPrivateChatArea(text) {
    $("#privChatAreaPn").jqxPanel("append", "<p class='chatAreaElement'>" + text + "</p>");

    // Set chat area scroll position
    $("#privChatAreaPn").jqxPanel("scrollTo", 0, $("#privChatAreaPn").jqxPanel("getScrollHeight"));
}

function writeToGameChatArea(text) {
    $("#gameChatAreaPn").jqxPanel("append", "<p class='chatAreaElement'>" + text + "</p>");

    // Set chat area scroll position
    $("#gameChatAreaPn").jqxPanel("scrollTo", 0, $("#gameChatAreaPn").jqxPanel("getScrollHeight"));
}

function populateBigRoomList() {
//    var rooms = sfs.roomManager.getRoomListFromGroup();
    var source = new Array("<h1>Giản đơn 1</h1>",
        "<h1>Giản đơn 2</h1>",
        "<h1>Giản đơn 3</h1>",
        "<h1>Chuẩn 1</h1>",
        "<h1>Chuẩn 2</h1>",
        "<h1>Chuẩn 3</h1>");

    $("#bigroomList").jqxListBox({source: source});
    if (LOBBY_ROOM == CHO_1) {
        $("#bigroomList").jqxListBox("selectedIndex", 0);
    } else if (LOBBY_ROOM == CHO_2) {
        $("#bigroomList").jqxListBox("selectedIndex", 1);
    } else if (LOBBY_ROOM == CHO_3) {
        $("#bigroomList").jqxListBox("selectedIndex", 2);
    } else if (LOBBY_ROOM == CHO_4) {
        $("#bigroomList").jqxListBox("selectedIndex", 3);
    } else if (LOBBY_ROOM == CHO_5) {
        $("#bigroomList").jqxListBox("selectedIndex", 4);
    } else if (LOBBY_ROOM == CHO_6) {
        $("#bigroomList").jqxListBox("selectedIndex", 5);
    }
//    $("#bigroomList").jqxListBox("selectedIndex",0);
//    $("#bigroomList").jqxListBox()
    //    Set selected index
//    $("#bigroomList").jqxListBox("selectedIndex", selectedIndex);
}

function populateRoomsList(event) {
    if (sfs.lastJoinedRoom == null) {
        return;
    }
    var id = getIdGroup();
    var rooms = sfs.roomManager.getRoomListFromGroup(sfs.lastJoinedRoom.groupId);

    var source = [];
    var response = event.params.rooms;
    var selectedRoom = ($("#roomList").jqxListBox("selectedIndex") > -1 ? $("#roomList").jqxListBox("getSelectedItem").originalItem.roomObj.id : null);
    var selectedIndex;
    var index = 0;
    if (rooms != null) {
        for (var i = 0; i < rooms.length; i++) {
            var room = rooms[i];
            if (room.isGame) {
                for (var j = 0; j < response.length; j++) {
                    if (room.name == response[j].roomName) {
                        var count = response[j].userCount;
                        var item = initItemRoom(count, room, response[j].users, id, i);
                        source.push(item);
                        if (room.id == selectedRoom)
                            selectedIndex = index;
                        index++;
                        break;
                    }
                }
            }
        }
    }

    $("#roomList").jqxListBox({source: source});

    // Set selected index
//    $("#roomList").jqxListBox("selectedIndex", selectedIndex);
}

function updateRoomList(event) {
    if (sfs.lastJoinedRoom == null) {
        return;
    }
    var id = getIdGroup();
    var rooms = sfs.roomManager.getRoomListFromGroup(sfs.lastJoinedRoom.groupId);
    var response = event.params;

    if (rooms != null) {
        var roomNotGame = 0;
        for (var i = 0; i < rooms.length; i++) {
            var room = rooms[i];
            if (room.isGame) {
                if (room.name == response.roomName) {
                    var html;
                    if (response.userInRoom == null) {
                        html = initHTMLRoomItem(0, room, null, id, i);
                    } else {
                        html = initHTMLRoomItem(response.userInRoom.length, room, response.userInRoom, id, i);
                    }

                    $("#roomList").jqxListBox('updateAt', {html: html }, i - roomNotGame);
                }
            } else {
                roomNotGame++;
            }
        }
    }
}

function getIdGroup() {
    var id;
    if (sfs.lastJoinedRoom.name == CHO_1) {
        id = 1;
    } else if (sfs.lastJoinedRoom.name == CHO_2) {
        id = 2;
    } else if (sfs.lastJoinedRoom.name == CHO_3) {
        id = 3;
    } else if (sfs.lastJoinedRoom.name == CHO_4) {
        id = 4;
    } else if (sfs.lastJoinedRoom.name == CHO_5) {
        id = 5;
    } else if (sfs.lastJoinedRoom.name == CHO_6) {
        id = 6;
    }

    return id;
}

function initItemRoom(count, room, users, id, i) {
    var item = {};
    item.html = initHTMLRoomItem(count, room, users, id, i);
    item.title = room.name;
    item.roomObj = room;
    return item;
}

function initHTMLRoomItem(count, room, users, id, i) {
//    var imgurl = 'images/avatar.jpg';
    var imgbg = 'images/bg_item_room.png';
//    var img = '<img style="padding-left: 10px;padding-right: 10px;vertical-align: middle" height="40" width="40" src="' + imgurl + '"/>'
    var stype = "style=' padding-left: 25px; background-image: url(" + imgbg + ");'";
    var html;
    var bdiv = "<div class='bdiv' style='height: 30px'>";
    var div1 = "<div class='div1'>";
    var div2 = "<div class='div2'>";
    var div3 = "<div class='div3'>";
    var div4 = "<div class='div4'>";
    if (count == 0) {
        html = div1 + "<h2 class='itemTitle game'><strong> Bàn " + id + "." + i + "</h2></div>" + div2 + "</div>" + div3 + "<h3> vs </h3></div>" + div4 + "</div>";
    } else if (count == 1) {
        html = div1 + "<h2 class='itemTitle game'><strong> Bàn " + id + "." + i + "</h2></div>" + div2 + "<h4>" + users[0] + "</div>" + div3 + "<h3> vs </h3></div>" + div4 + "</div>";
    } else {
        html = div1 + "<h2 class='itemTitle game'><strong> Bàn " + id + "." + i + "</h2></div>" + div2 + "<h4>" + users[0] + "</h4></div>" + div3 + "<h3> vs </h3></div>" + div4 + "<h5>" + users[1] + "</h5></div>";
    }
    return html;
}

function populateUsersList() {
    var index = 0;
    enableButton("#inviteUserBt", false);

    // "main" indicates the main user list contained in the right accordion of the lobby view

    var mainSource = [];
    var mainSelectedIndex = -1;
//	var mainSelectedUser = ($("#userList").jqxListBox("selectedIndex") > -1 ? $("#userList").jqxListBox("getSelectedItem").title : null);
    var mainSelectedUser;
    if (sfs.lastJoinedRoom != null && (sfs.lastJoinedRoom.name == CHO_1 || sfs.lastJoinedRoom.name == CHO_2
        || sfs.lastJoinedRoom.name == CHO_3 || sfs.lastJoinedRoom.name == CHO_4
        || sfs.lastJoinedRoom.name == CHO_5 || sfs.lastJoinedRoom.name == CHO_6)) {
//        var users = sfs.lastJoinedRoom.getUserList();
        var users = sfs.lastJoinedRoom.getUserList();
        for (var u in users) {
            var user = users[u];
            var imgurl = 'images/avatar.jpg';
            var mainItem = {};
            var img = '<img style="padding-right: 5px; vertical-align: middle" height="30" width="30" src="' + imgurl + '"/>'
            mainItem.html = "<div><p class='itemTitle1'><strong>" + img + user.name + "</strong></p>";

            // Private Messages
            if (privateChats[user.id] != null && privateChats[user.id].toRead > 0)
                mainItem.html += "<p class='itemSub toRead'>" + privateChats[user.id].toRead + " PM to read</p>";

            mainItem.html += "</div>";

            mainItem.title = user.name;
            mainItem.userObj = user;

            mainSource.push(mainItem);

            if (user.name == mainSelectedUser || (currentPrivateChat > -1 && user.id == currentPrivateChat))
                mainSelectedIndex = index;

            index++;
        }
    }

    // Populate list
    $("#userList").jqxListBox({source: mainSource});

    // Set selected index
    $("#userList").jqxListBox("selectedIndex", mainSelectedIndex);

    // Make sure selected index is visible
    if (mainSelectedIndex > -1)
        $("#userList").jqxListBox("ensureVisible", mainSelectedIndex + 1);
}
function onAvatar() {
    var source;
    var mainItem = {};
    var imgurl = 'images/avatar.jpg';

    if(myInfo.getVariable("variables").value.honourable==1){
        honourable = "đồng";
    }else if(myInfo.getVariable("variables").value.honourable==2){
        honourable = "bạc";
    }else if(myInfo.getVariable("variables").value.honourable==3){
        honourable = "vàng";
    }

    var img = '<img height="80" width="80" src="' + imgurl + '"/>';
    mainItem.html = "<div  style='float: left; padding-top: 5px'>" + img + "</div>"+
        "<div style='float: left; padding-left: 5px; padding-top: 5px'><p class='itemTitle1'><strong>" + "Tên: " + myInfo.name + "</br>"
        + "Thắng: " + myInfo.getVariable("variables").value.totalWin + "</br>"
        + "Tổng: " + myInfo.getVariable("variables").value.totalGame + "</br>"
        + "Điểm: " + myInfo.getVariable("variables").value.point + "</br>"
        + "Danh hiệu: " + honourable + "</strong></p></div>";

    source = mainItem;
    $("#avatar").jqxListBox({source: source});
//    $("#avatar").jqxListBox('disableAt', 0 );
}

function oninfo() {
    $("#avatar").jqxListBox("unselectIndex",0);
}
function onEnterKey() {
    if (sfs.lastJoinedRoom == null) {
        return 1;
    }
    else if (sfs.lastJoinedRoom.name == LOBBY_ROOM)
        return 2;

    return 0;
}
function logregister(){
    var imail = $("#emailInput").val();
    var username = $("#userInput").val();
    var password = $("#passwordInput").val();
    var passwordcf = $("#passwordConfirmInput").val();
    console.log("em: "+imail +"\n us: " + username +"\npass: "+password+"\npasscf: "+passwordcf);
}
